package cc.mrbird.charging.controller;

import cc.mrbird.charging.domain.Charging;
import cc.mrbird.charging.service.ChargingService;
import cc.mrbird.common.annotation.Log;
import cc.mrbird.common.controller.BaseController;
import cc.mrbird.common.domain.QueryRequest;
import cc.mrbird.common.domain.ResponseBo;
import cc.mrbird.submission.domain.PullDown;
import cc.mrbird.submission.domain.SubmissionEntry;
import cc.mrbird.submission.util.RestUtil;
import cc.mrbird.submission.util.WXPayUtil;
import com.alibaba.druid.sql.visitor.functions.Char;
import org.apache.poi.hssf.usermodel.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class ChargingController extends BaseController {
    @Value("${uploadPath}")
    private String uploadPath;

    @Autowired
    private ChargingService chargingService;

    @RequestMapping("charging")
    public String charging(Model model) {

        return "charging/charging";
    }

    @Log("增加投诉信息")
    @RequestMapping("charging/addCharging")
    @ResponseBody
    public ResponseBo addCharging(Charging charging, @RequestPart(value="pic",required = false) MultipartFile pic) throws Exception {
        if(charging.getPaymentChannels().equals("undefined")){
            charging.setPaymentChannels(null);
        }
        if(charging.getComplaintChannels().equals("undefined")){
            charging.setComplaintChannels(null);
        }
        if(charging.getProcessingResults().equals("undefined")){
            charging.setProcessingResults(null);
        }
        if(charging.getComplaintType().equals("undefined")){
            charging.setComplaintType(null);
        }
        if(charging.getContactInformation().equals("undefined")){
            charging.setContactInformation(null);
        }
        if(charging.getRegistrar().equals("undefined")){
            charging.setRegistrar(null);
        }
        if(charging.getHandler().equals("undefined")){
            charging.setHandler(null);
        }
        if(charging.getRemakes().equals("undefined")){
            charging.setRemakes(null);
        }
        if(charging.getContentsComplaints().equals("undefined")){
            charging.setContentsComplaints(null);
        }
        if(charging.getProcessing().equals("undefined")){
            charging.setProcessing("26");
        }
        if(charging.getFirst().equals("undefined")){
            charging.setFirst("48");
        }
        if(pic != null){
            String str = pic.getOriginalFilename();
            //截取图片名字之前字符串
            String str1=str.substring(0, str.indexOf("."));
            String frontPicName = str1+String.valueOf((int)((Math.random()*9+1)*1000000000));
            //截取图片名字之后字符串
            String str2=str.substring(0, str.indexOf("."));
            String afterPicName = str.substring(str2.length()+1, str.length());

            String picName = uploadPath + frontPicName+"."+afterPicName;
            File picFile = new File(picName);
            pic.transferTo(picFile);
            charging.setPicName(frontPicName+"."+afterPicName);
        }
        System.out.println("处理结果:"+charging.getProcessingResults());
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(currentTime);
        charging.setAcceptanceTime(dateString);
        charging.setFeedback(null);
        //charging.setProcessing("26");
        if(charging.getFirst() == null){
            charging.setFirst("48");
        }
        chargingService.saveCharging(charging);
        String subid = chargingService.findId();
        Long id = super.getCurrentUser().getUserId();
        //190
        if(id == 190){
            WXPayUtil wxPayUtil = new WXPayUtil();
            Map map = new HashMap();
            String idNotice = "111";
            String content = null;
            if(charging.getFirst().equals("48")){
                content = "你好，前台人员有提交新的充电桩投诉信息，投诉编号为："+subid+"，请注意查看";
            }else if(charging.getFirst().equals("47")){
                content = "你好，优先处理的充电桩投诉信息，投诉编号为："+subid+"，请注意查看！";
            }

            String keyid = "2";
            String random_number = wxPayUtil.generateNonceStr();
            String time_stamp = String.valueOf(System.currentTimeMillis());
            String key = "EL6UjSc4U1it6vaFrQ9GlGiMicEbRc0P";
            //通知编号
            map.put("id",idNotice);
            //通知内容
            map.put("content",content);
            //keyid
            map.put("keyid",keyid);
            //随机数
            map.put("random_number",random_number);
            //时间戳
            map.put("time_stamp",time_stamp);
            String sign = wxPayUtil.generateSignature(map,key);
            String url = "http://120.77.182.149:8999/OpenApi/tyxNotice";
            System.out.println(url);
            String data = "id="+idNotice+"&content="+content+"&keyid="+keyid+"&random_number="+random_number+"&time_stamp="+time_stamp+"&sign="+sign;

            RestUtil restUtil = new RestUtil();
            restUtil.interfaceUtil(url,data);
        }
        return ResponseBo.ok();
    }

    @Log("动态获取下拉选")
    @RequestMapping("charging/pullDown")
    @ResponseBody
    public List<PullDown> FindPullDown(PullDown pullDown ) {

        return chargingService.FindPullDown(pullDown);

    }

    @Log("获取投诉信息列表")
    @RequestMapping("charging/chargingList")
    @ResponseBody
    public Map<String, Object> submissionList(QueryRequest request, Charging charging) {
        return super.selectByPageNumSize(request, () -> this.chargingService.getChargingList(charging));
    }

    @Log("增加选配置")
    @RequestMapping("charging/addChargingDown")
    @ResponseBody
    public ResponseBo addPullDown(PullDown pullDown )throws Exception {

        PullDown pullDown1 = chargingService.savePullDown(pullDown);
        if(pullDown1 == null){
            chargingService.addPullDown(pullDown);
            return ResponseBo.ok();
        }else{
            return ResponseBo.error("已存在！请重新填写");
        }
    }

    @Log("根据id获取投诉信息")
    @RequestMapping("charging/getChargingId")
    @ResponseBody
    public ResponseBo getBySubmissionId(Charging charging) {
        String id = charging.getId();
        charging.setId(id);
        return ResponseBo.ok().put("data",chargingService.getChargingId(charging));
    }

    @Log("修改投诉信息")
    @RequestMapping("charging/updateCharging")
    @ResponseBody
    public ResponseBo updateSubmission(Charging charging, @RequestPart(value="pic",required = false) MultipartFile pic) throws Exception {
        if(pic != null){
            String str = pic.getOriginalFilename();
            //截取图片名字之前字符串
            String str1=str.substring(0, str.indexOf("."));
            String frontPicName = str1+String.valueOf((int)((Math.random()*9+1)*1000000000));
            //截取图片名字之后字符串
            String str2=str.substring(0, str.indexOf("."));
            String afterPicName = str.substring(str2.length()+1, str.length());

            String picName = uploadPath + frontPicName+"."+afterPicName;
            File picFile = new File(picName);
            pic.transferTo(picFile);
            charging.setPicName(frontPicName+"."+afterPicName);
        }
        Long id = super.getCurrentUser().getUserId();
        if(id == 190){
            charging.setProcessing("未处理");
        }
        if(charging.getProcessing().equals("已处理")||charging.getProcessing()=="已处理"){
            Date currentTime = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateString = formatter.format(currentTime);
            charging.setProcessingTime(dateString);
        }
        String processingTime = charging.getProcessingTime();
        if(processingTime == ""){
            System.out.println("processingTime: "+processingTime);
            charging.setProcessingTime(null);
        }
        chargingService.updateCharging(charging);
        return ResponseBo.ok();
    }

    @Log("投诉信息撤销")
    @RequestMapping("charging/cancelCharging")
    @ResponseBody
    public ResponseBo cancelSubmission(Charging charging )throws Exception{

        chargingService.cancelCharging(charging);
        return ResponseBo.ok();
    }

    @Log("优先处理数量")
    @RequestMapping("charging/first")
    @ResponseBody
    public PullDown first(){
        PullDown pullDown = new PullDown();
        pullDown.setSubmissionValue(chargingService.sumFirst());
        return pullDown;
    }


    /**
     * 投诉系统发送短信给客户
     * @return
     * @throws Exception
     */
                /* 客户您好，充电金额已原路退回您的扣款账户，请留意查收。感谢您的理解祝您生活愉快！ */
    @RequestMapping("charging/chargingFebsNotice")
    @ResponseBody
    public ResponseBo chargingFebsNotice(String id,String phone,String value) throws Exception {

        WXPayUtil wxPayUtil = new WXPayUtil();
        Map map = new HashMap();
        String idNotice = "110";
        String keyid = "2";
        String random_number = wxPayUtil.generateNonceStr();
        String time_stamp = String.valueOf(System.currentTimeMillis());
        String key = "EL6UjSc4U1it6vaFrQ9GlGiMicEbRc0P";
        //通知编号
        map.put("id",idNotice);
        //通知内容
        //客户您好，充电金额已原路退回您的扣款账户，请留意查收。感谢您的理解祝您生活愉快！
        //keyid
        map.put("keyid",keyid);
        //电话号码
        map.put("phone",phone);
        //随机数
        map.put("random_number",random_number);
        //时间戳
        map.put("time_stamp",time_stamp);
        String sign = wxPayUtil.generateSignature(map,key);
        String url = "http://120.77.182.149:8999/OpenApi/febsChargingNotice";
        System.out.println(url);
        String data = "id="+idNotice+"&phone="+phone+"&keyid="+keyid+"&random_number="+random_number+"&time_stamp="+time_stamp+"&sign="+sign;
        RestUtil restUtil = new RestUtil();
        restUtil.interfaceUtil(url,data);
        Charging charging = new Charging();
        charging.setId(id);
        String context = "客户您好，充电金额已原路退回您的扣款账户，请留意查收。感谢您的理解祝您生活愉快！";
        charging.setFeedback(context);
        chargingService.updateCharging(charging);
        return ResponseBo.ok();
    }

    /**
     * 导出投诉信息
     * @param response
     * @param charging
     * @return
     */
    @RequestMapping("charging/exportExcel")
    @ResponseBody
    public Object exportExcel(HttpServletResponse response, Charging charging){

        ServletOutputStream outputStream = null;
        HSSFWorkbook workbook = null;
        try {
            // 创建 excel 文件
            workbook = new HSSFWorkbook();
            // 创建一个标签页
            HSSFSheet sheet = workbook.createSheet("用户信息");

            //设置列宽
            sheet.setColumnWidth(0, 3000);
            sheet.setColumnWidth(1, 3000);
            sheet.setColumnWidth(2, 3000);
            sheet.setColumnWidth(3, 3000);
            sheet.setColumnWidth(4, 3000);
            sheet.setColumnWidth(5, 3000);
            sheet.setColumnWidth(6, 3000);
            sheet.setColumnWidth(7, 3000);
            sheet.setColumnWidth(8, 3000);
            sheet.setColumnWidth(9, 3000);
            sheet.setColumnWidth(10, 3000);
            sheet.setColumnWidth(11, 3000);


            //创建格式
            HSSFCellStyle titleStyle = workbook.createCellStyle();
            titleStyle.setWrapText(true);
            titleStyle.setAlignment(HSSFCellStyle.VERTICAL_CENTER);//水平居中
            titleStyle.setVerticalAlignment(HSSFCellStyle.ALIGN_CENTER);//垂直居中


            HSSFFont titleFont = workbook.createFont();
            titleFont.setBold(true);//粗体
            titleFont.setFontHeightInPoints((short)12);//大小
            titleFont.setFontName("宋体");//字体类型
            titleStyle.setFont(titleFont);

            // 创建标题行
            HSSFRow titleRow = sheet.createRow(0);

            HSSFCell cell0 = titleRow.createCell(0);
            cell0.setCellValue("投诉编号");
            cell0.setCellStyle(titleStyle);

            HSSFCell cell1 = titleRow.createCell(1);
            cell1.setCellValue("受理时间");
            cell1.setCellStyle(titleStyle);

            HSSFCell cell2 = titleRow.createCell(2);
            cell2.setCellValue("支付渠道");
            cell2.setCellStyle(titleStyle);

            HSSFCell cell3 = titleRow.createCell(3);
            cell3.setCellValue("投诉渠道");
            cell3.setCellStyle(titleStyle);

            HSSFCell cell4 = titleRow.createCell(4);
            cell4.setCellValue("投诉类别");
            cell4.setCellStyle(titleStyle);

            HSSFCell cell5 = titleRow.createCell(5);
            cell5.setCellValue("联系方式");
            cell5.setCellStyle(titleStyle);

            HSSFCell cell6 = titleRow.createCell(6);
            cell6.setCellValue("投诉内容");
            cell6.setCellStyle(titleStyle);

            HSSFCell cell7 = titleRow.createCell(7);
            cell7.setCellValue("处理结果");
            cell7.setCellStyle(titleStyle);

            HSSFCell cell8 = titleRow.createCell(8);
            cell8.setCellValue("登记人");
            cell8.setCellStyle(titleStyle);

            HSSFCell cell9 = titleRow.createCell(9);
            cell9.setCellValue("处理时间");
            cell9.setCellStyle(titleStyle);

            HSSFCell cell12 = titleRow.createCell(10);
            cell12.setCellValue("处理人");
            cell12.setCellStyle(titleStyle);


            HSSFCell cell11 = titleRow.createCell(11);
            cell11.setCellValue("处理情况");
            cell11.setCellStyle(titleStyle);


            //DB查询数据
            List<Charging> userList = chargingService.getChargingExportExcel(charging);
            System.out.println(userList);
            if(userList == null || userList.isEmpty()){
                return ("导出数据失败，无投诉信息！");
            }


            // 封装excel数据
            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            for (int i = 0; i < userList.size(); i++) {
                System.out.println(userList.size());
                titleRow = sheet.createRow(i + 1);
                //投诉编号
                titleRow.createCell(0).setCellValue(userList.get(i).getId());
                //受理时间
                titleRow.createCell(1).setCellValue(userList.get(i).getAcceptanceTime());
                //支付渠道
                titleRow.createCell(2).setCellValue(userList.get(i).getPaymentChannels());
                //投诉渠道
                titleRow.createCell(3).setCellValue(userList.get(i).getComplaintChannels());
                //投诉类别
                titleRow.createCell(4).setCellValue(userList.get(i).getComplaintType());
                //联系方式
                titleRow.createCell(5).setCellValue(userList.get(i).getContactInformation());
                //投诉内容
                titleRow.createCell(6).setCellValue(userList.get(i).getContentsComplaints());
                //处理结果
                titleRow.createCell(7).setCellValue(userList.get(i).getProcessingResults());
                //登记人
                titleRow.createCell(8).setCellValue(userList.get(i).getRegistrar());
                //处理时间
                titleRow.createCell(9).setCellValue(userList.get(i).getProcessingTime());
                //处理人
                titleRow.createCell(10).setCellValue(userList.get(i).getHandler());
                //处理情况
                titleRow.createCell(11).setCellValue(userList.get(i).getProcessing());


            }
            // 设置两个头 一个输出流
            String filename = "投诉信息表.xls";
            try {
                outputStream = response.getOutputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 响应信息，弹出文件下载窗口
            response.setContentType("APPLICATION/OCTET-STREAM");
            try {
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "utf-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            try {
                workbook.write(outputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }

            return ResponseBo.error("导出数据失败！");
        } finally {
            try {
                if (outputStream != null) {
                    workbook.close();
                    outputStream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
                return ResponseBo.error( "导出数据失败！" + e.getMessage());
            }

        }
    }
}
